package com.hsq.commons.util.db.ibatisExecutor;

import javax.annotation.PostConstruct;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.stereotype.Service;
import com.hsq.commons.util.beans.BeanUtils;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.engine.execution.SqlExecutor;
import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient;

@Service("baseIbatisDao")
public abstract class BaseIbatisDao extends SqlMapClientDaoSupport   {

	@Autowired
    private SqlExecutor sqlExecutor;

    @Autowired
    public void init(@Qualifier("sqlMapClient")SqlMapClient sqlMapClient,@Qualifier("dataSource")BasicDataSource dataSource ){
    	this.setSqlMapClient(sqlMapClient);
    	this.setDataSource(dataSource);
    }

    public void setEnableLimit(boolean enableLimit) {
        if (sqlExecutor instanceof LimitSqlExecutor) {
            ((LimitSqlExecutor) sqlExecutor).setEnableLimit(enableLimit);
        }
    }

  
    @PostConstruct
    public void initialize() throws Exception {
        if (sqlExecutor != null) {
            SqlMapClient sqlMapClient = getSqlMapClientTemplate().getSqlMapClient();
            if (sqlMapClient instanceof ExtendedSqlMapClient) {
                BeanUtils.setFieldValue(((ExtendedSqlMapClient) sqlMapClient).getDelegate(),
                		"sqlExecutor",
                		SqlExecutor.class,
                        sqlExecutor);
            }
        }
    }

   

}
